package com.adnaan.restaurant.controller;

import com.adnaan.restaurant.common.config.FileUpload;
import com.adnaan.restaurant.common.exception.BizException;
import com.adnaan.restaurant.common.untils.R;
import com.adnaan.restaurant.common.untils.SecurityUtils;
import com.adnaan.restaurant.entity.LoginUserVo;
import com.adnaan.restaurant.entity.SysUser;
import com.adnaan.restaurant.service.ISysUserService;
import com.alibaba.fastjson2.JSON;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * author: adnaan
 * create: 2023-11-22 15:43
 * Description:
 */
@Tag(name = "用户接口", description = "用户相关功能")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private FileUpload fileUpload;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public R login(@RequestBody LoginUserVo loginUserVo) {

        SysUser sysUser = sysUserService.selectUserByUserName(loginUserVo.getUsername());
        if (sysUser == null) {
            /*return R.error(404, "用户不存在");*/
            throw new BizException(404, "该用户不存在");
        }

        boolean ok = SecurityUtils.matchesPassword(loginUserVo.getPassword(), sysUser.getPassword());
        if (ok) {
            String token = UUID.randomUUID().toString().replace("-", "");
            System.out.println(token);

            stringRedisTemplate.opsForValue().set(token, JSON.toJSONString(sysUser), 1, TimeUnit.HOURS);

            String json = stringRedisTemplate.opsForValue().get(token);
            SysUser userInfo = JSON.parseObject(json, SysUser.class);
            userInfo.setToken(token);

            return R.success("登录成功").put("data", userInfo);
        } else {
            return R.error(500, "登录失败");
        }
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/getUser")
    public R getUser(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String json = stringRedisTemplate.opsForValue().get(token);

        if (json == null) {
            return R.error("用户登录信息已过期");
        } else {
            SysUser sysUser = JSON.parseObject(json, SysUser.class);
            return R.success(sysUser);
        }
    }

    @Operation(summary = "修改用户信息")
    @PutMapping("/updateUser")
    public R updateUser(@RequestBody SysUser sysUser, HttpServletRequest request) {

        if (sysUser.getPassword() != null) {
            sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        } else {
            sysUser.setPassword(sysUserService.selectUserByUserId(sysUser.getUserId()).getPassword());
        }
        int updateStatus = sysUserService.updateUser(sysUser);
        if (updateStatus > 0) {
            SysUser detail = sysUserService.selectUserByUserId(sysUser.getUserId());
            stringRedisTemplate.opsForValue().set(request.getHeader("Authorization"), JSON.toJSONString(detail), 1, TimeUnit.HOURS);
            return R.success("修改成功");
        } else {
            return R.error(500, "修改失败");
        }
    }

    @Operation(summary = "用户上传头像")
    @PostMapping("/uploadAvatar")
    public R uploadAvatar(@RequestParam MultipartFile file, @RequestParam Long userId, HttpServletRequest request) {
        String url = fileUpload.upload(file, "avatar");
        int avatar = sysUserService.updateAvatar(url, userId);
        if (avatar > 0) {
            SysUser detail = sysUserService.selectUserByUserId(userId);
            stringRedisTemplate.opsForValue().set(request.getHeader("Authorization"), JSON.toJSONString(detail), 1, TimeUnit.HOURS);
            return R.success("上传成功").put("avatarUrl", url);
        } else {
            return R.error(500, "上传失败");
        }
    }

    @Operation(summary = "获取用户id")
    @GetMapping("/Info")
    public R getInfo(HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        System.out.println("当前用户id:" + userId);
        return R.success();
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public R register(@RequestBody SysUser user) {
        SysUser isRepeat = sysUserService.selectUserByUserName(user.getUserName());
        if (isRepeat != null) {
            throw new BizException(409, "用户名重复,请换一个试试");
        }
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        if (sysUserService.register(user) == 1) {
            return R.success("注册成功");
        } else {
            throw new BizException("无法注册，请联系管理员");
        }
    }

    @Operation(summary = "用户退出")
    @PostMapping("/loginOut")
    public R loginOut(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (Boolean.TRUE.equals(stringRedisTemplate.delete(token))) {
            return R.success("退出成功");
        } else {
            throw new BizException("数据不存在");
        }
    }
}
